from TileCache import TileCache
from helpers import * #@UnusedWildImport
from Sprite import * #@UnusedWildImport
from Camera import Camera
from Level import Level

map_cache = TileCache(MAP_TILE_WIDTH, MAP_TILE_HEIGHT)

class Game(object):

    def __init__(self, saveFile="game01"):
        self.screen = pygame.display.get_surface()
        self.saveFile = saveFile
        self.spriteCache = TileCache()
        self.tileCache = TileCache(32,32)
        self.sprites = SortedUpdates()
        self.loadLevel(Level())
        self.camera = Camera()
        
    def update(self, screen):
        self.sprites.clear(screen, self.terrain)
        self.sprites.update()
    
    def save(self):
        pass
    
    def display(self):
        x , y, w, h = self.camera.get_bounds()
        for i in range (w / 2 / MAP_TILE_WIDTH + 1):
            for j in range (h / MAP_TILE_HEIGHT / 2 + 2):
                self.screen.blit(self.background, (i*2*MAP_TILE_WIDTH - (x%(MAP_TILE_WIDTH*4))/2, j*2*MAP_TILE_HEIGHT - (y%(MAP_TILE_HEIGHT*4)/2)))        
        self.screen.blit(self.terrain, (-x, -y))
        #dirty=self.sprites.draw(self.screen)
        #self.overlays.draw(self.screen)
        #pygame.display.update(dirty)   
        
    def handleEvents(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                return False
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return False
        x, y, w, h = self.camera.get_bounds()
        if self.keyIsDown(K_RIGHT) and (x+w+5) <= (self.level.width * MAP_TILE_WIDTH):
            self.camera.move_x(5)
        elif self.keyIsDown(K_LEFT) and (x) >= 5:
            self.camera.move_x(-5)
        if self.keyIsDown(K_UP) and y >= 5:
            self.camera.move_y(-5)
        elif self.keyIsDown(K_DOWN) and (y+h+5) <= (self.level.height * MAP_TILE_HEIGHT):
            self.camera.move_y(5)       
        return True

    def keyIsDown(self, key):
        keystate=pygame.key.get_pressed()
        if keystate[key]:
            return True
        return False
    
    def loadLevel(self, level):
        self.sprites = SortedUpdates()
        self.overlays = pygame.sprite.RenderUpdates()
        self.level = level
        for pos, tile in level.items.iteritems():
            sprite = Sprite(pos, self.spriteCache[tile["sprite"]])
            
            self.sprites.add(sprite)
            
            self.terrain, overlays, self.background = self.level.render()
            for (x, y), image in overlays.iteritems():
                overlay = pygame.sprite.Sprite(self.overlays)
                overlay.image = image
                overlay.rect = image.get_rect().move(x*MAP_TILE_WIDTH, y*MAP_TILE_HEIGHT - MAP_TILE_HEIGHT)
        self.terrain, overlays, self.background = self.level.render()
        